import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'


// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 18000 // request timeout
})
// request interceptor 请求拦截器
service.interceptors.request.use(
  config => {
    // 让每个请求携带标记 token
    if (getToken()) {
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor 响应拦截器
service.interceptors.response.use(
  response => {
    // console.log('形影拦截器response.data',response.data); 
    const res = response.data
    if (res.type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" || res.type =="text/xml" ) {
      return res
    }
    console.log('状态码',res.code);
    
    if (res.code !== 200) {
      if (res.code === 10001) {
        MessageBox.confirm(res.msg, '请重新登录!', {
          confirmButtonText: '确认',
          showCancelButton: false, //不显示取消按钮
          type: 'error'
        }).then(() => {
          store.dispatch('user/logout').then(() => {
            location.reload()
          })
        }).catch(() => { })
      } else {
        MessageBox.confirm(res.msg ? res.msg : '接口出错啦!', '请确认以下信息', {
          confirmButtonText: '确认',
          showCancelButton: false, //不显示取消按钮
          type: 'error'
        }).then(() => { }).catch(() => { })
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: "响应失败",
      type: 'error',
      duration: 1 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
